package com.yitiao.controller;

import cn.hutool.core.date.StopWatch;
import com.yitiao.entity.EsBlog;
import com.yitiao.es.EsBlogRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/blog")
public class BlogController {
    @Resource
    private EsBlogRepository esBlogRepository;

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    // 模糊搜索
    @GetMapping("/search")
    public String getContent(String keyWord) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
//        Iterable<EsBlog> esBlogs = esBlogRepository.findAll();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.should(QueryBuilders.matchPhraseQuery("title", keyWord));
        builder.should(QueryBuilders.matchPhraseQuery("content", keyWord));
        String s = builder.toString();
        System.out.println("--------s:" + s);
        Page<EsBlog> blogs = (Page<EsBlog>) esBlogRepository.search(builder);
        List<EsBlog> esBlogs = blogs.getContent();
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        return esBlogs.toString() + "  耗时：" + totalTimeMillis;
    }
}
